import { ref } from 'vue'

type LoadingConfig = {
  delayTime: number
  timeoutTime: number // 自动关闭loading的时间
}

const defaultConfig: LoadingConfig = {
  delayTime: 500,
  timeoutTime: 10000
}

type LoadingInfo = {
  tip?: string
}

export default (config: Partial<LoadingConfig> = {}) => {
  const { delayTime, timeoutTime } = { ...defaultConfig, ...config }
  const isLoading = ref(false)
  let loadingTimeoutTimer: any = null
  const loadingInfo = ref<LoadingInfo>({
    tip: ''
  })
  let startLoadingTime = 0
  let endLoadingTime = 0

  let closeDebounceTimer: any = null

  const openLoading = (info: Partial<LoadingInfo> = {}) => {
    loadingTimeoutTimer && clearTimeout(loadingTimeoutTimer)

    loadingInfo.value = { ...info }
    closeDebounceTimer && clearTimeout(closeDebounceTimer)
    isLoading.value = true
    startLoadingTime = Date.now()

    loadingTimeoutTimer = setTimeout(closeLoading, timeoutTime)
  }
  const closeLoading = () => {
    endLoadingTime = Date.now()
    const time = endLoadingTime - startLoadingTime
    if (time < delayTime) {
      closeDebounceTimer = setTimeout(() => {
        isLoading.value = false
      }, delayTime - time)
      return
    }

    isLoading.value = false
  }

  return { openLoading, isLoading, closeLoading, loadingInfo }
}
